package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.me

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityGhanaMeBinding
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.hitPoint
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.declaration.DeclarationGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.declaration.PrivacyPolicyGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.declaration.ThirdSdkUsageGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.feedback.FeedbackGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.mydoc.MyDocGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.myprofile.MyProfileGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.mywallet.MyWalletGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.setting.SettingGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.subview.HotlineGhanaDialog
import org.json.JSONObject

class MeGhanaActivity : AppCompatActivity() {

    private lateinit var myWalletViewModel: MeGhanaViewModel
    private lateinit var binding: ActivityGhanaMeBinding
    private lateinit var adapter: MeGhanaPageAdapter

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        myWalletViewModel = ViewModelProvider(this)[MeGhanaViewModel::class.java]

        // 关联布局
        binding = ActivityGhanaMeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val hotline = binding.navbarRight
        val back = binding.navbarLeft
        val list = binding.list
        val loading = binding.loading

        // 初始化adapter
        adapter = MeGhanaPageAdapter(emptyList())
        list.layoutManager = LinearLayoutManager(this)
        list.adapter = adapter

        // 页面loading状态接口监听
        myWalletViewModel.loadingResult.observe(this@MeGhanaActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面详情接口监听
        myWalletViewModel.pageDetailResult.observe(this@MeGhanaActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (pageDetailResult.error != null) {
                // TODO: 失败
                showMessage(pageDetailResult.error)
                return@Observer
            }
            if (pageDetailResult.success != null) {
                // 渲染
                adapter.dataList = pageDetailResult.success
                adapter.notifyDataSetChanged()
            }
        })

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineGhanaDialog().showNow(supportFragmentManager, "hotline")
            hitPoint("SHOW_HOTLINE")
        }

        // 点击返回
        back.setOnClickListener {
            finish()
        }

        // 点击 my profile
        binding.myProfile.setOnClickListener {
            hitPoint("ME_MY_PROFILE_CLICK")

            val intent = Intent(this@MeGhanaActivity, MyProfileGhanaActivity::class.java)
            startActivity(intent)
        }

        // 点击 my wallet
        binding.myWallet.setOnClickListener {
            hitPoint("ME_MY_WALLET_CLICK")

            val intent = Intent(this@MeGhanaActivity, MyWalletGhanaActivity::class.java)
            startActivity(intent)
        }

        // 点击 more doc
        binding.myMoreDoc.setOnClickListener {
            hitPoint("ME_MORE_DOC_CLICK")

            val intent = Intent(this@MeGhanaActivity, MyDocGhanaActivity::class.java)
            startActivity(intent)
        }

        // 点击 declaration
        binding.declaration.setOnClickListener {
            hitPoint("ME_DECLARATION_CLICK")
            val intent = Intent(this@MeGhanaActivity, DeclarationGhanaActivity::class.java)
            startActivity(intent)
        }

        // 点击 feedback
        binding.feedback.setOnClickListener {
            hitPoint("ME_FEEDBACK_CLICK")
            val intent = Intent(this@MeGhanaActivity, FeedbackGhanaActivity::class.java)
            startActivity(intent)
        }

        // 点击 privacy policy
        binding.privacyPolicy.setOnClickListener {
            hitPoint("ME_PRIVACY_CLICK")
            val intent = Intent(this@MeGhanaActivity, PrivacyPolicyGhanaActivity::class.java)
            startActivity(intent)
        }

        // 点击 third sdk
        binding.thirdSdk.setOnClickListener {
            hitPoint("ME_THIRD_SDK_CLICK")
            val intent = Intent(this@MeGhanaActivity, ThirdSdkUsageGhanaActivity::class.java)
            startActivity(intent)
        }

        // 点击 setting
        binding.setting.setOnClickListener {
            hitPoint("ME_SETTING_CLICK")
            val intent = Intent(this@MeGhanaActivity, SettingGhanaActivity::class.java)
            startActivity(intent)
        }

        // 点击 home
        binding.tabHome.setOnClickListener {
            finish()
        }

        // 填充姓名电话
        binding.mobile.text = ProjectApplication.mobAction(isGet = true)

        // 查询页面详情
        myWalletViewModel.pageDetail()
    }

    fun showMessage(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }

    override fun onResume() {
        super.onResume()
        hitPoint(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPoint(type = this::class.java.simpleName, isPageEnd = true)
    }
}

class MeGhanaPageAdapter(
    var dataList: List<JSONObject>
) :
    RecyclerView.Adapter<MeGhanaPageAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_ghana_hotline_dialog_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val title: TextView = view.findViewById(R.id.title)
        val action: TextView = view.findViewById(R.id.action)
        val tips: TextView = view.findViewById(R.id.tips)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item: JSONObject = dataList[position]

        val isMobile = item.optInt("type", 0)
        if (isMobile == 0) {
            holder.action.text = "Dial"
            holder.tips.text = "Customer service hotline ${position + 1}"
        } else {
            holder.action.text = "Copy"
            holder.tips.text = "Customer service Email ${position + 1}"
        }

        val contact = item.optString("title")
        holder.title.text = contact

        holder.action.setOnClickListener {
            if (isMobile == 0) {
                val intent = Intent(Intent.ACTION_DIAL).apply {
                    data = Uri.parse("tel:${Uri.encode(contact)}")
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK
                }
                ProjectApplication.instance.startActivity(intent)

            } else {
                val clipboardManager =
                    ProjectApplication.instance.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                clipboardManager.setPrimaryClip(ClipData.newPlainText("Label", contact))

                Toast.makeText(
                    ProjectApplication.instance,
                    "Copy Success",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}